<template>
  <div class="finance-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>财务管理</h1>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAddFinance">
        <el-icon><Plus /></el-icon> 新增财务记录
      </el-button>
      <el-button type="success" @click="handleImport">
        <el-icon><Upload /></el-icon> 导入数据
      </el-button>
      <el-button type="info" @click="handleExport">
        <el-icon><Download /></el-icon> 导出数据
      </el-button>
      <el-button type="warning" @click="handleBatchOperate">
        <el-icon><More /></el-icon> 批量操作
      </el-button>
    </div>

    <!-- 筛选条件区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="交易类型">
          <el-select v-model="filterForm.type" placeholder="请选择交易类型">
            <el-option label="全部" value="all"></el-option>
            <el-option label="收入" value="income"></el-option>
            <el-option label="支出" value="expense"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="交易状态">
          <el-select v-model="filterForm.status" placeholder="请选择交易状态">
            <el-option label="全部" value="all"></el-option>
            <el-option label="待审核" value="pending"></el-option>
            <el-option label="已审核" value="approved"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="关联订单号">
          <el-input v-model="filterForm.orderNo" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>

        <el-form-item label="供应商">
          <el-input v-model="filterForm.supplierName" placeholder="请输入供应商名称" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="data-table-card">
      <div class="table-container">
        <el-loading v-loading="tableLoading" element-loading-text="加载中...">
          <el-table
            :data="financeList"
            border
            size="small"
            highlight-current-row
            @selection-change="handleSelectionChange"
            :header-cell-style="{ 'background-color': '#f5f7fa' }"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column prop="financeNo" label="财务单号" min-width="140" show-overflow-tooltip></el-table-column>
            <el-table-column prop="orderNo" label="关联订单号" min-width="140" show-overflow-tooltip></el-table-column>
            <el-table-column prop="supplierName" label="供应商" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="type" label="交易类型" min-width="90">
              <template #default="scope">
                <el-tag :type="scope.row.type === 'income' ? 'success' : 'danger'">
                  {{ scope.row.type === 'income' ? '收入' : '支出' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额(元)" min-width="110" align="right">
              <template #default="scope">{{ scope.row.amount.toFixed(2) }}</template>
            </el-table-column>
            <el-table-column prop="transactionDate" label="交易日期" min-width="120"></el-table-column>
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人" min-width="100" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" min-width="180" fixed="right">
              <template #default="scope">
                <el-button type="text" size="small" @click="handleViewDetail(scope.row)">查看</el-button>
                <el-button type="text" size="small" v-if="['pending'].includes(scope.row.status)" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="text" size="small" v-if="['pending'].includes(scope.row.status)" @click="handleApprove(scope.row)">审核</el-button>
                <el-button type="text" size="small" danger v-if="['pending', 'approved'].includes(scope.row.status)" @click="handleCancel(scope.row)">取消</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <div class="table-summary">
              <span>共 <strong>{{ pagination.total }}</strong> 条记录，</span>
              <span>收入总额：<strong class="text-success">{{ totalIncome.toFixed(2) }} 元</strong>，</span>
              <span>支出总额：<strong class="text-danger">{{ totalExpense.toFixed(2) }} 元</strong>，</span>
              <span>净额：<strong :class="totalNet >= 0 ? 'text-success' : 'text-danger'">{{ totalNet.toFixed(2) }} 元</strong></span>
            </div>
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            ></el-pagination>
          </div>
        </el-loading>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  Plus,
  Upload,
  Download,
  More
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 定义财务记录类型
interface FinanceRecord {
  id: string;
  financeNo: string;
  orderNo: string;
  supplierName: string;
  type: 'income' | 'expense';
  amount: number;
  transactionDate: string;
  status: 'pending' | 'approved' | 'rejected' | 'cancelled';
  operator: string;
  remark?: string;
}

// 路由实例
const router = useRouter();

// 筛选表单数据
const filterForm = reactive({
  type: 'all',
  status: 'all',
  dateRange: [] as string[],
  orderNo: '',
  supplierName: ''
});

// 表格加载状态
const tableLoading = ref(true);

// 选中的行数据
const selectedRows = ref<FinanceRecord[]>([]);

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 财务列表数据
const financeList = ref<FinanceRecord[]>([]);

// 统计数据
const totalIncome = ref(0);
const totalExpense = ref(0);
const totalNet = ref(0);

// 获取状态文本
const getStatusText = (status: string): string => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已审核',
    'rejected': '已拒绝',
    'cancelled': '已取消'
  };
  return statusMap[status] || '未知';
};

// 获取状态标签类型
const getStatusTagType = (status: string): string => {
  const typeMap = {
    'pending': 'info',
    'approved': 'success',
    'rejected': 'danger',
    'cancelled': 'warning'
  };
  return typeMap[status] || 'default';
};

// 选择项变化
const handleSelectionChange = (val: FinanceRecord[]) => {
  selectedRows.value = val;
};

// 查询数据
const handleQuery = () => {
  tableLoading.value = true;
  // 模拟API请求
  setTimeout(() => {
    generateFinanceData();
    tableLoading.value = false;
  }, 800);
};

// 重置筛选条件
const handleReset = () => {
  filterForm.type = 'all';
  filterForm.status = 'all';
  filterForm.dateRange = [];
  filterForm.orderNo = '';
  filterForm.supplierName = '';
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  tableLoading.value = true;
  setTimeout(() => {
    generateFinanceData();
    tableLoading.value = false;
  }, 800);
};

// 当前页码变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  tableLoading.value = true;
  setTimeout(() => {
    generateFinanceData();
    tableLoading.value = false;
  }, 800);
};

// 查看详情
const handleViewDetail = (row: FinanceRecord) => {
  router.push({ name: 'FinanceDetail', params: { id: row.id } });
};

// 新增财务记录
const handleAddFinance = () => {
  router.push({ name: 'FinanceAdd' });
};

// 编辑财务记录
const handleEdit = (row: FinanceRecord) => {
  router.push({ name: 'FinanceEdit', params: { id: row.id } });
};

// 审核财务记录
const handleApprove = async (row: FinanceRecord) => {
  try {
    await ElMessageBox.confirm(`确定要审核通过财务记录 ${row.financeNo} 吗？`, '审核确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    });

    // 模拟API请求
    setTimeout(() => {
      // 更新本地数据
      const index = financeList.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        financeList.value[index].status = 'approved';
      }
      ElMessage.success('审核通过成功');
    }, 800);
  } catch (error) {
    // 用户取消操作
  }
};

// 取消财务记录
const handleCancel = async (row: FinanceRecord) => {
  try {
    const inputResult = await ElMessageBox.prompt(`请输入取消财务记录 ${row.financeNo} 的原因`, '取消确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入取消原因',
      type: 'warning'
    });

    const reason = inputResult.value.trim();
    if (!reason) {
      ElMessage.warning('取消原因不能为空');
      return;
    }

    // 模拟API请求
    setTimeout(() => {
      // 更新本地数据
      const index = financeList.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        financeList.value[index].status = 'cancelled';
      }
      ElMessage.success('取消成功');
    }, 800);
  } catch (error) {
    // 用户取消操作
  }
};

// 导入数据
const handleImport = () => {
  ElMessage.info('导入功能开发中...');
};

// 导出数据
const handleExport = () => {
  ElMessageBox.confirm('确定要导出当前财务数据吗？', '导出数据', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    // 模拟导出延迟
    setTimeout(() => {
      ElMessage.success('数据导出成功');
    }, 1000);
  }).catch(() => {
    // 用户取消导出
  });
};

// 批量操作
const handleBatchOperate = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要操作的记录');
    return;
  }

  ElMessageBox.confirm(`确定要对选中的 ${selectedRows.value.length} 条记录执行批量操作吗？`, '批量操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    // 模拟批量操作
    setTimeout(() => {
      ElMessage.success('批量操作成功');
      selectedRows.value = [];
    }, 800);
  }).catch(() => {
    // 用户取消操作
  });
};

// 生成财务数据
const generateFinanceData = () => {
  // 生成模拟数据
  const mockData: FinanceRecord[] = [];
  const statuses: ('pending' | 'approved' | 'rejected' | 'cancelled')[] = ['pending', 'approved', 'rejected', 'cancelled'];
  const suppliers = ['供应商A', '供应商B', '供应商C', '供应商D', '供应商E', '供应商F', '供应商G'];
  const operators = ['张三', '李四', '王五', '赵六', '钱七'];

  // 生成当前页数据
  for (let i = 0; i < pagination.pageSize; i++) {
    const index = (pagination.currentPage - 1) * pagination.pageSize + i + 1;
    const isIncome = Math.random() > 0.4;
    const amount = Math.floor(Math.random() * 100000) + 10000;
    const statusIndex = Math.floor(Math.random() * statuses.length);
    const date = new Date();
    date.setDate(date.getDate() - Math.floor(Math.random() * 90));
    const formattedDate = date.toISOString().slice(0, 10);

    mockData.push({
      id: `finance-${index}`,
      financeNo: `FIN${Date.now() - index * 1000}`,
      orderNo: `ZCY${Date.now() - index * 10000}`,
      supplierName: suppliers[Math.floor(Math.random() * suppliers.length)],
      type: isIncome ? 'income' : 'expense',
      amount: isIncome ? amount : -amount,
      transactionDate: formattedDate,
      status: statuses[statusIndex],
      operator: operators[Math.floor(Math.random() * operators.length)],
      remark: `这是一条${isIncome ? '收入' : '支出'}记录的备注信息`
    });
  }

  // 设置总条数
  pagination.total = 156;

  // 更新表格数据
  financeList.value = mockData;

  // 计算统计数据
  calculateSummary();
};

// 计算统计数据
const calculateSummary = () => {
  let income = 0;
  let expense = 0;

  financeList.value.forEach(item => {
    if (item.type === 'income') {
      income += item.amount;
    } else {
      expense += Math.abs(item.amount);
    }
  });

  totalIncome.value = income;
  totalExpense.value = expense;
  totalNet.value = income - expense;
};

// 页面加载时初始化
onMounted(() => {
  // 设置默认日期范围为最近30天
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(endDate.getDate() - 30);
  filterForm.dateRange = [
    startDate.toISOString().slice(0, 10),
    endDate.toISOString().slice(0, 10)
  ];

  // 加载数据
  handleQuery();
});
</script>

<style scoped lang="scss">
.finance-list-container {
  padding: 0 20px;
}

.page-header {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  padding: 10px 0;
}

.data-table-card {
  margin-bottom: 20px;
}

.table-container {
  overflow-x: auto;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-summary {
  font-size: 14px;
  color: #606266;
}

.text-success {
  color: #67C23A;
}

.text-danger {
  color: #F56C6C;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .finance-list-container {
    padding: 0 10px;
  }

  .action-buttons {
    flex-wrap: wrap;
  }

  .filter-form {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-form .el-form-item {
    margin-bottom: 15px;
    width: 100%;
  }

  .pagination-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>